import json
import os
import json

def read_rust_code(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:
            rust_code = file.read()
        return rust_code
    except UnicodeDecodeError:
        return ""


def replace_prefix(file_path, prefix_original, prefix_new):
    if file_path.startswith(prefix_original):
        return file_path.replace(prefix_original, prefix_new, 1)
    else:
        return file_path  # 如果路径不匹配，则返回原始路径



def extract_error_messages(input_string):
    error_messages = []
    # 按照\n分割字符串
    parts = input_string.split('\n')

    # 遍历每个子字符串
    for part in parts:
        # 检查子字符串是否以"error[E"开头
        if part.startswith('error[E'):
            error_messages.append(part)

    return error_messages

def read_json(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到。")
    except json.JSONDecodeError:
        print(f"文件 {file_path} 不是有效的JSON文件。")
    except Exception as e:
        print(f"读取文件 {file_path} 时发生错误: {e}")


def path_normalized(file_path):
    normalized_path = os.path.normpath(file_path)
    normalized_path = normalized_path.replace('\\', '/')
    return normalized_path

# 适用于list和dict
def save_data_to_json(data, file_path):
    # 创建目录
    os.makedirs(os.path.dirname(file_path), exist_ok=True)
    with open(file_path, 'w', encoding='utf-8') as json_file:
        json.dump(data, json_file, ensure_ascii=False, indent=4)

def save_data_to_rs(data, rs_path):
    os.makedirs(os.path.dirname(rs_path), exist_ok=True)
    with open(rs_path, 'w', encoding='utf-8') as rs_file:
        rs_file.write(data)


def total_dict_lengths(json_file_path):
    total_length = 0

    # 读取 JSON 文件
    with open(json_file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)

        # 遍历每个字典
        for key, value in data.items():
            total_length += len(value)

    return total_length


def get_first_level_subdirectories(directory):
    subdirectories = []
    for item in os.listdir(directory):
        item_path = os.path.join(directory, item)
        if os.path.isdir(item_path):
            subdirectories.append(item_path)
    return subdirectories


# 提取路径的前n级，不适用于相对路径
def get_n_levels_subdirectory(path, n):
    # 将路径按分隔符分割
    parts = path.split(os.sep)
    limited_parts = parts[:n]
    return os.sep.join(limited_parts)


# 通过"/"提取路径的前n级
def get_n_levels_subdirectory_base_string(path, n):
    # 以'/'为分隔符分割路径
    parts = path.split("/")

    # 提取前 n 级，并确保结果为目录格式（带/）
    limited_parts = parts[:n]

    # 重新组合成路径
    return "/".join(limited_parts) + "/" if limited_parts else ""


def get_last_directory_name(path):
    return os.path.basename(os.path.normpath(path))


'''
input: 文件路径file_path, 要添加的内容new_content
output: 文件已被修改，返回原始文件的内容
'''
def modify_rs_file(file_path, new_content):
    # 1. 读取原始文件内容
    with open(file_path, 'r', encoding='utf-8') as file:
        original_content = file.read()

    # 2. 将新内容添加到文件末尾
    with open(file_path, 'a', encoding='utf-8') as file:
        file.write("\n" + new_content)

    # print(f"新内容已添加到 {file_path}")

    return original_content

'''
恢复文件
'''
def restore_rs_file(original_content, file_path):
    # 4. 恢复原始文件内容
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(original_content)

    # print(f"{file_path} 已恢复为原始状态")


def perform_operations(file_path):
    # 3. 在这里执行你需要的操作
    print(f"正在执行对 {file_path} 的操作...")

    # 示例：运行一些命令
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
        print(content)
    # os.system(f"cargo check")  # 示例操作，可以根据需要替换

# # 示例用法
# directory = '../dataset/crates/crates'
# first_level_subdirs = get_first_level_subdirectories(directory)
# print(first_level_subdirs)



# # 示例用法
# json_file_path = '../result/test_funcname_match.json'  # 替换为你的 JSON 文件路径
# total_length = total_dict_lengths(json_file_path)
# print(f"所有字典的长度总和是: {total_length}")